package com.jiaai.filter;

import com.jiaai.auth.model.UserEntity;
import com.jiaai.auth.util.JWTEncryptUtil;
import com.jiaai.util.ResponseUtils;
import com.jiaai.util.RestResultGenerator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * class_name:BackAdminInterceptor
 * describe:TODO
 * create_user:张昉平
 * create_date:2017/12/22
 * create_date:12:01
 */
public class BackAdminInterceptor extends HandlerInterceptorAdapter {

    private static final Logger xlog = LoggerFactory.getLogger(BackAdminInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //防止跨域
        ResponseUtils.setHeaderCors(response);
        if (request.getMethod().equals("OPTIONS")){
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            response.setStatus(401);
            ResponseUtils.responseData(response, RestResultGenerator.genErrorResult(401, "请登录"));
            return false;
        } else {
            try {
                UserEntity user = JWTEncryptUtil.decryptUserToken(token);
                String name = user.getUserName();

                if (StringUtils.isEmpty(name)){
                    response.setStatus(401);
                    ResponseUtils.responseData(response, RestResultGenerator.genErrorResult(401, "请登录"));
                    return false;
                }else {
                    request.setAttribute("userName", name);
                    request.setAttribute("auths", user.getAuths());
                    return true;
                }
            }catch (Exception e){
                response.setStatus(401);
                ResponseUtils.responseData(response, RestResultGenerator.genErrorResult(401, "请登录"));
                return false;
            }
        }
    }
}
